/* 
    对数据库查重验证
*/

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator'

import mongoose from 'mongoose'

@ValidatorConstraint({ name: 'customText', async: false })
export class isExist implements ValidatorConstraintInterface {
  async validate(text: string, args: ValidationArguments) {
    //如果存在返回错误信息
    await mongoose.connect('mongodb://localhost/blog')
    const schema = mongoose.model(args.constraints[0].name, args.constraints[1])
    const result = await schema.findOne({ [args.property]: text })

    if (result) {
      return false
    }

    return true // for async validations you must return a Promise<boolean> here
  }

  defaultMessage(args: ValidationArguments) {
    // here you can provide default error message if validation failed
    return 'Text ($value) is too short or too long!'
  }
}
